<template>
  <van-nav-bar :title="newsData.title || '标题'" left-arrow @click-left="onClickLeft" @click-right="onClickRight">
    <template #right>
      <van-icon name="wap-home-o" size="18" />
    </template>
  </van-nav-bar>

  <div v-if="loading" class="loading-container">
    <van-skeleton :row="2"  class="my-skeleton-title"/>
    <van-skeleton :row="2"  class="my-skeleton-editor"/>
    <van-skeleton :row="1"  class="my-skeleton-content"/>
  </div>

  <div v-else-if="error" class="error-container">
    <van-icon name="failure" size="48" color="#ff4757" />
    <p class="error-text">加载失败，请重试</p>
    <van-button type="primary" @click="fetchNewsDetail()">重新加载</van-button>
  </div>

  <div v-else class="pd30">
    <div class="news-title">
      {{ newsData.title }}
    </div>
    <div class="news-maker">
      新闻作者：{{ newsData.editor || '未知作者' }}
    </div>
    <div class="news-creat-time">
      发布时间：{{ safeFormatRelativeTime(newsData.releasetime) }}
    </div>
    <div class="news-content" v-html="newsData.bodys || '暂无内容'">
    </div>
  </div>
  <!-- <div class="other-news">
    <div class="title pd30">
      相关新闻
    </div>
    <van-list>
      <van-cell v-for="item in 3" :key="item" class="news-box">
        <nuxt-link :to="'/news/' + item" class="flex"> 
          <div class="news-text">
            <h2 class="title">
              花开好了，发布邀您赴一场郑州春天的约会！
            </h2>
            <p class="date">
              3小时前
            </p>
          </div>
          <div class="news-img">
            <van-image :src="`/new${item}.jpg`" width="128" height="72" fit="contain" />
          </div>
        </nuxt-link>
      </van-cell>
    </van-list>
  </div> -->
  <div class="news-comment">
    <div class="title pd30">
      评论
    </div>
    <div class="comment-box">
      <div class="flex center">
        <van-image src="https://static.zhengguannews.cn/wap/assets/images/comment.png" width="120" fit="contain" />
      </div>

    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { navigateTo, useRoute } from 'nuxt/app';     
 

// 获取路由参数
const route = useRoute();
const newsId = computed(() => route.params.news as string);
const cid = computed(() => route.query.cid as string || '');


// 定义新闻详情数据类型
interface NewsDetail {
  id: string;
  title: string;
  content: string;
  posttime: string;
  author: string;
  picurl: string;
  hits: string;
  classid: string;
  [key: string]: any;
}
const newsData = ref<NewsDetail>({} as NewsDetail);
const loading = ref(false);
const error = ref(false);


//时间格式化
const dayjs = useDayjs();

const safeFormatRelativeTime = (time: string | null | undefined) => {
  if (!time) return '';
  const now = dayjs();
  const target = dayjs(time);
  
  // 如果是当天时间，显示相对时间（如 "2 小时前"）
  if (target.isSame(now, 'day')) {
    return target.fromNow();
  } 
  // 非当天时间，显示完整年月日（如 "2023-01-01"）
  return target.format('YYYY-MM-DD');
};

// 格式化日期 

//获取新闻数据


// 获取新闻详情数据
const fetchNewsDetail = async () => {
  if (!newsId.value) return;
  
  try {
        loading.value = true;
    // 使用本地API端点  
    const responseData = await $fetch('/api/news/detail', {
      params: {
        newsid: newsId.value        
      }
    });  
    // 检查响应数据是否存在
    if (responseData?.data) { 
       newsData.value = responseData.data[0];
       console.log(newsData.value);  
        } else {
            // 处理无数据情况
            console.error('未获取到新闻数据');
            error.value = true; 
        }
  } catch (err: any) {
    console.error('获取新闻详情失败:', err.message || err);
        error.value = true;  
  } finally {
        loading.value = false;
    console.log('请求处理完成');
  }
}; 


//返回上一页
const onClickLeft = () => {
 history.back();
};

//返回首页

const onClickRight = () => {
    navigateTo('/');
}


// 组件挂载时获取数据
onMounted(() => {
  fetchNewsDetail();
});
</script>


<style scoped>
  .news-title{
    font-size: 28px;
    line-height: 32px;
    padding: 40px 0 20px;
  }

  .my-skeleton-title{
    padding: 40px 15px 20px;
  }
   .my-skeleton-title :deep(.van-skeleton-paragraph){
    height: 32px;
  }

  .my-skeleton-content :deep(.van-skeleton-paragraph){
    min-height: calc(100vh - 150px);
    margin-top: 30px;
    width: 100% !important;
  }
 
  
  .news-maker, .news-creat-time{
    font-size: 12px;
    color: #999;
    line-height: 16px;
    margin-bottom: 6px;
  }

  .news-content{
    margin-top: 30px;
  }

 
  :deep(.news-content *) {
      font-size: 17px;
      line-height: 30px;
      color: #000;
  }

   :deep(.news-content img) {
      width: calc(100% + 30px);
      margin: 12px -15px !important;
  }
 :deep(.news-content video) {
      width: calc(100% + 30px);
      margin: 12px -15px;
  }
  .other-news,
  .news-comment{
    margin-top: 40px;
    padding-bottom: 60px;
  }
</style>